/*###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############*/


document.captureEvents = false;

JFX_AdminBlocks = function(options){
    var me = this;
    this.registerEventListener('doRebuildPage_exit', function(){me.drawToolbar();
		AdminBlocks.registerEventListener('doRebuildPage_exit', function(){});
	});
    this.fullScreen = false;
    this.numBlocks = Array();
    this.menuMapper = Array();
    this.urlMapper = Array();
    this.blockMapper = Array();
    this.elementForInserting = '';
    this.menuHoverId = '';
    this.page = new Object;
    this.mode = options.mode;
    this.ajaxUrl = JFXConfig.ajaxUrl;
    this.pageid = options.pageid;
    this.templateid = options.templateid;
    this.workspaceid = options.workspaceid;
    this.page.id = 'jfxpage-'+options.pageid;
	this.pageId = this.page.id;
    this.page.details = options.pageDetails;
    this.rebuildPage();
    this.templatePageId = options.templatePageId;
    this.menuMapper = Array();
    this.urlMapper = Array();
    this.initMenu();
}

/**
 * JFX_AdminBlocks extends JFX_Base
 */
JFX_AdminBlocks.prototype = new JFX_Base();


JFX_AdminBlocks.prototype.drawToolbar = function(){
    this.tabber = new JFX_AdminTabber(this);
    var val = $('#jfx-toolbar-buttons .jfx-block-buttons img').get(0);
    if(val && $(val).triggerEvent) $(val).triggerEvent('click');
    if(this.page.elements.length > 0){
        this.tabber.focusTab(this.page.elements[0].details.id);
    }
	this.registerEventListener('doRebuildPage_exit', function(){});
}



/**
 * Initialize the menu system - display the toolbar
 * begin TODO: remove the url/menu mappers, replace with page load call to display menu
 */
JFX_AdminBlocks.prototype.initMenu = function(){
    $('#jfx-pages').click(function(){
        AdminBlocks.pages = this;
        $('#jfx-pages-menu').show('slow');
    }, function(){})

    this.menuMapper['jfx-toolbar'] = $('#jfx-toolbar').get(0);
    this.menuMapper['jfx-pages'] = $('#jfx-pages-menu').get(0);

    this.urlMapper['jfx-toolbar'] = 'toolbar/';
    this.urlMapper['jfx-pages'] = 'pages-menu/';

    $('#jfx-block-order').click(function(){
        var href = JFXConfig.ajaxUrl+'/block-execution-order/?page='+AdminBlocks.pageid+'&KeepThis=true&TB_iframe=true&height=500&width=700';
        tb_show('Editing Block Execution Order', href, false);
    });
}
JFX_AdminBlocks.prototype.getMenuContent = function(itemId){
    if(typeof(this.urlMapper[itemId])!=='string') return;
    this.menuHoverId = itemId;
    $.get(this.ajaxUrl+'/'+this.urlMapper[itemId]+'?page='+AdminBlocks.pageid, this.showMenuContent);
}

JFX_AdminBlocks.prototype.showMenuContent = function(text){
    AdminBlocks.parseContent(AdminBlocks.menuHoverId, text);
}

JFX_AdminBlocks.prototype.parseContent = function(menuId, text){
    var menuContent = this.menuMapper[menuId];
    switch(menuId){
        case 'jfx-toolbar':
			if($('#jfx-pages-menu').draggable){
				$('#jfx-toolbar').draggable({handle : '#jfx-toolbar-header'});
			}
			if($('#jfx-pages-menu').resizable){
				$('#jfx-toolbar').resizable();
			}
            JFXToolbarHide();

        break;
        case 'jfx-pages':
                    // first example
            AdminBlocks.menuMapper[AdminBlocks.menuHoverId].innerHTML = text;
            $("#jfx-page-tree").treeview({
                persist: "location",
                collapsed: true,
                unique: true
            });
            $('#jfx-pages-menu-inner a.edit-page').unbind('click');
            $('#jfx-pages-menu-inner a.edit-page').click(function(){
                var href = JFXConfig.ajaxUrl+'/edit-page/?page='+AdminBlocks.pageid+'&KeepThis=true&TB_iframe=true&height=500&width=700';
                tb_show('Editing Page Details', href, false);
            });

        break;
    }
}
JFX_AdminBlocks.prototype.getBlockDetails = function(blockId){
    $.getJSON(this.ajaxUrl+'/get-block-details/', {blockId : blockId, pageid : AdminBlocks.page.id}, this.storeBlockDetails);
}

JFX_AdminBlocks.prototype.storeBlockDetails = function(json){
    AdminBlocks.setValue('blockMapper_'+json.id, json);
}
/**
 * end TODO: remove the url/menu mappers, replace with page load call to display menu
 */






/**
 * Fetch the JSON data for all page elements, then invoke the method to draw the dom
 */
JFX_AdminBlocks.prototype.rebuildPage = function(){
    this.log('rebuildPage :'+this.mode);
	JFXShowLoadingAnimation();
    this.page.elements = Array();
    switch(this.mode){
        case 'template' :
            $.getJSON(this.ajaxUrl+'/get-template-elements/', {template : this.templateid}, this.doRebuildPage);
        break;
        case 'page' :
            $.getJSON(this.ajaxUrl+'/get-page-elements/', {page : this.pageid}, this.doRebuildPage);
        break;
    }

}
/**
 * Invoked by rebuildPage, obtains page data as json from prior ajax request, draws dom elements
 */
JFX_AdminBlocks.prototype.doRebuildPage = function(page){
    // build each page element

	JFXHideLoadingAnimation();

	$('#'+AdminBlocks.pageId).html('');

	AdminBlocks.page = page;
	AdminBlocks.pageId = page.id;

	AdminBlocks.addPageActions();


	for(var i=0; i<page.elements.length; i++){
        AdminBlocks.addElement(page.elements[i].details.id, AdminBlocks.pageId); // creates actions too
    }

    AdminBlocks.trigg('doRebuildPage_exit');

}

JFX_AdminBlocks.prototype.addPageActions = function(){
	var blockActions, blockHeading, blockActionsWrapper;

	blockActions = document.createElement('div');
	blockActions.id = 'jfx-actions_'+AdminBlocks.page.id;
	$(blockActions).addClass('jfx-actions');

	blockHeading = document.createElement('h3');
	$(blockHeading).text(AdminBlocks.page.title);
	$(blockActions).append(blockHeading);

	blockActionsWrapper = document.createElement('div');
	$(blockActionsWrapper).addClass('jfx-actions-button-wrapper');
	$(blockActionsWrapper).html(AdminBlocks.page.action_buttons);
	$(blockActions).append(blockActionsWrapper);

	$('#'+AdminBlocks.pageId).append(blockActions);

}



JFX_AdminBlocks.prototype.addElement = function(blockId, parentId){
	var block;
	
	block = AdminBlocks.findElement(AdminBlocks.page.elements, blockId);

	if(block==false){
		return;
	}

	// let's build this block
	var blockDom, blockActions, blockActionsWrapper, blockContent, blockHeading;

	blockDom = document.createElement('div');
	blockDom.id = block.id;
	$(blockDom).addClass('jfx-block');
	$(blockDom).addClass(block.details.class_name);

	if(block.details.is_droppable){
		$(blockDom).addClass('jfx-droppable');
	}

	blockActions = document.createElement('div');
	blockActions.id = 'jfx-actions_'+block.id;
	$(blockActions).addClass('jfx-actions');
	$(blockDom).append(blockActions);

	blockHeading = document.createElement('h3');
	$(blockHeading).text(block.title);
	$(blockActions).append(blockHeading);

	blockActionsWrapper = document.createElement('div');
	$(blockActionsWrapper).addClass('jfx-actions-button-wrapper');
	$(blockActionsWrapper).html(block.action_buttons);
	$(blockActions).append(blockActionsWrapper);

	blockContent = document.createElement('div');
	$(blockContent).addClass('jfx-content-area');
	$(blockContent).html(block.content);
	$(blockDom).append(blockContent);

	$('#'+parentId).append(blockDom);

	// child elements
	if(block.elements && block.elements.length){
		for(var i=0; i<block.elements.length; i++){
			AdminBlocks.addElement(block.elements[i].id, block.id);
		}
	}

}



/**
* Called by an event handler to make visible actions for selected block and hide all other actions
*/
JFX_AdminBlocks.prototype.showMyActions = function(el){
    var actionsEl = $('#jfx-actions_'+el.id).get(0);
    $(actionsEl).css('display', 'block');
    AdminBlocks.visibleActions = actionsEl;
    AdminBlocks.log('showing actions for '+el.id);
}


/**
 * Apply block content
 */
JFX_AdminBlocks.prototype.insertBlockContent = function(content){
    $('#'+content.id+' .jfx-content-area').get(0).innerHTML = content.content;
    $('#'+content.id+' .jfx-content-area form').get(function(){
        this.action = 'javascript: void(null)';
    });
}







/**
 * Automatically save the page.
 */
JFX_AdminBlocks.prototype.autoSavePage = function(){
    var useResponseFunction = true;
    var responseFunction = this.confirmSavePage;
    this.savePage(useResponseFunction, responseFunction);
}
/**
 * Save the page, manually supply response function
 */
JFX_AdminBlocks.prototype.savePage = function(useResponseFunction, responseFunction){
    if(useResponseFunction!==true){
        this.callSaveResponseFunction = false;
        this.saveResponseFunction = responseFunction;
    }else{
        this.callSaveResponseFunction = true;
        this.saveResponseFunction = responseFunction;
    }


    var json = JSON.stringify(this.page);

    //var json = this.page.serialize();
    var data = {
        'type' : 'post',
        'datatype' : 'json',
        'data' : json
    }
    $.post(JFXConfig.ajaxUrl+'/save-page/', data, this.confirmSave);
}
/**
 * Display confirmation or failure after page save
 */
JFX_AdminBlocks.prototype.confirmSavePage = function(success, message){
    if(success){
        alert('Save successful!');
        //window.location = this.saveLocation;
    }else{
        alert('Error saving: '+message);
    }
}

/**
 * Display confirmation or failure after template save (deprecated)
 */
JFX_AdminBlocks.prototype.confirmSaveBlockTemplate = function(json){
    json = JSON.parse(json);
    alert('JFX_AdminBlocks.saveTemplate is deprecated, please use Website Content > Templates');
    if(json.status == 'OK') alert('Save success!');
}



























JFX_AdminBlocks.prototype.toggleFullScreen = function(){
    if(this.fullScreen === true){
        $('.jfxt-banner, .jfxt-footer-full').slideDown('slow');
        $('.jfxt-black-menu').css('z-index', 0);
        this.fullScreen = false;
    }else{
        $('.jfxt-banner, .jfxt-footer-full').slideUp('slow');
        $('.jfxt-black-menu').css('z-index', 2);
        this.fullScreen = true;
    }
}


/**
 * Toggle the view mode to full-screen or normal
 *
JFX_AdminBlocks.prototype.toggleFullScreen = function(){
    var pageEl, newParent, menuEl;
    menuEl = $('.jfxt-black-menu').get(0);
    pageEl = $('#jfx-page-workspace').get(0);
    if(this.fullScreen){
        // restore to normal
        $(menuEl).css({
            'position' : 'relative',
            'top' : '0'
        });
        $(pageEl).css({
            'position' : 'relative',
            'top' : '0'
        });
        $('.jfxt-banner, .jfxt-footer-full').css({
            'display' : 'block'
        });
        clearTimeout(this.hideFullScreenTabTimeout);
        
        newParent = $('#jfx-workspace-wrapper').get(0);
        $(pageEl).prependTo(newParent);
       
        this.fullScreen = false;
    }else{
        // display full-screen
        newParent = $('body').get(0);
        $(pageEl).prependTo(newParent);
        $(menuEl).css({
            'position' : 'absolute',
            'left' : '0',
            'top' : '0',
            'width' : '100%',
            'z-index' : 2
        });
        $(pageEl).css({
            'top' : (menuEl.clientHeight+16)+'px',
            'position' : 'absolute',
            'z-index' : '2'
        });
        $('.jfxt-banner, .jfxt-footer-full').css({
            'display' : 'none'
        });
        this.fullScreen = true;
    }
}

















/**
 * Obtain the details of the parent element
 * var parentEl = this.findParent(this.page, myEl.id);
 */
JFX_AdminBlocks.prototype.findParent = function(el, id){
    if(el.elements.length == 0) return false;
    var parentNode = el;
    for(var i=0; i<el.elements.length; i++){
        if(el.elements[i].id == id){
            return parentNode;
        }
        else if(el.elements[i].elements.length > 0){
            var found = this.findParent(el.elements[i], id);
            if(typeof(found) == 'object'){
                return found;
            }
        }
    }
    return false;
}

/**
 * Find the data key in a set of elements where an id is known
 *
 */
JFX_AdminBlocks.prototype.findKey = function(el, id){
    if(el.elements.length == 0) return false;
    for(var i=0; i<el.elements.length; i++){
        if(el.elements[i].id == id) return i;
    }
    return false
}

/**
 * Find an element in this.page, which contains all json data about page elements.
 * Returns array of data from JFX_Block::getDetails()
 */
JFX_AdminBlocks.prototype.findElement = function(elements, id){
    if(id == AdminBlocks.page.id){
        return AdminBlocks.page;
    }
    for(var i=0; i<elements.length; i++){
        if(elements[i].id == id){
            return elements[i];
        }
        else if(elements[i].elements.length > 0){
            var found = this.findElement(elements[i].elements, id);
            if(found !== false){
                return found;
            }
        }
    }
    return false;
}







